package com.tpshion.chat.controller;

import com.tpshion.chat.annotation.PassLogin;
import com.tpshion.chat.domain.dto.LoginDto;
import com.tpshion.chat.domain.dto.RegisterDto;
import com.tpshion.chat.domain.entity.Friend;
import com.tpshion.chat.domain.entity.UserInfo;
import com.tpshion.chat.domain.vo.LoginInfoVo;
import com.tpshion.chat.domain.vo.QueryFriendVo;
import com.tpshion.chat.domain.vo.UserInfoVo;
import com.tpshion.chat.exception.MyException;
import com.tpshion.chat.exception.RespStatus;
import com.tpshion.chat.exception.ResponseVo;
import com.tpshion.chat.service.FriendService;
import com.tpshion.chat.service.UserInfoService;
import com.tpshion.chat.utils.ImgUtil;
import com.tpshion.chat.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;


/**
 * @Description: 用户管理模块
 * @Author: tpshion
 * @Date: 2020/5/1 12:09
 * @Version: 1.0
 */
@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private FriendService friendService;

    @GetMapping(value = "/test")
    public ResponseVo<String> test(){
        return ResponseVo.ok("ok");
    }

    /**
     * 用户登录
     * @param loginDto
     * @param request
     * @return
     */
    @PostMapping(value = "/login")
    @PassLogin
    public ResponseVo login(@RequestBody LoginDto loginDto, HttpServletRequest request){
        //判断用户是否存在
        UserInfo userByUserName = userInfoService.findUserByUserName(loginDto.getUserName());
        if(userByUserName == null){
            //用户不存在
            throw new MyException(RespStatus.USER_NO_EXIST);
        }
        //判断用户密码是否正确
        if(!JwtUtil.checkpw(loginDto.getPassword(),userByUserName.getPassword())){
            //密码不正确
            throw new MyException(RespStatus.USER_PASSWORD_ERROR);
        }
        //获取用户token
        String token = JwtUtil.getToken(userByUserName.getUserId(), userByUserName.getUserName());
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userByUserName,userInfoVo);
        log.info("用户："+userInfoVo.getUserName()+" 登录系统, IP:"+request.getRemoteAddr()+", id:"+userInfoVo.getUserId());
        return ResponseVo.ok(new LoginInfoVo(userInfoVo,token));
    }

    /**
     * 注册用户
     * @param registerDto
     * @param request
     * @return
     */
    @PostMapping(value = "/register")
    @PassLogin
    public ResponseVo register(@RequestBody RegisterDto registerDto, HttpServletRequest request){
        //判断参数是否为空
        if(registerDto.getUserName() == null || registerDto.getPassword() == null){
            throw new MyException(RespStatus.PARAM_NOFUND);
        }
        //判断用户是否已存在
        UserInfo userByUserName = userInfoService.findUserByUserName(registerDto.getUserName());
        if(userByUserName != null){
            throw new MyException(RespStatus.USER_EXIST);
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(JwtUtil.getUUID());
        userInfo.setUserName(registerDto.getUserName());
        userInfo.setPassword(JwtUtil.hashpw(registerDto.getPassword()));
        userInfo.setNickName(registerDto.getUserName());
        userInfo.setUserImg(ImgUtil.generateImg(registerDto.getUserName()));
        userInfoService.addUserSelective(userInfo);
        log.info("新增用户："+userInfo.getUserName()+" IP:"+request.getRemoteAddr()+" id:"+userInfo.getUserId());
        return ResponseVo.ok("用户注册成功");
    }

    /**
     * 根据用户名称模糊查询用户
     * @param userId
     * @param searchKey
     * @return
     */
    @GetMapping(value = "/users")
    public ResponseVo<List<QueryFriendVo>> getUsersByUserName(
            @RequestParam("userId") String userId, @RequestParam("searchKey") String searchKey){
        List<UserInfoVo> userInfoVos = userInfoService.queryUserByUserName(searchKey);
        List<QueryFriendVo> queryFriendVos = new ArrayList<>();
        if(userInfoVos.size() > 0){
            int size = userInfoVos.size();
            for(int i=0; i<size; i++){
                UserInfoVo userInfoVo = userInfoVos.get(i);
                Friend friend = friendService.checkFriend(userId, userInfoVo.getUserId());
                if(friend == null){
                    QueryFriendVo queryFriendVo = new QueryFriendVo();
                    BeanUtils.copyProperties(userInfoVo,queryFriendVo);
                    queryFriendVos.add(queryFriendVo);
                }else {
                    QueryFriendVo queryFriendVo = new QueryFriendVo();
                    BeanUtils.copyProperties(userInfoVo,queryFriendVo);
                    queryFriendVo.setIsFriend(true);
                    queryFriendVos.add(queryFriendVo);
                }
            }
        }
        return ResponseVo.ok(queryFriendVos);
    }

    /**
     * 根据用户id查询用户信息
     * @param userId
     * @return
     */
    @GetMapping(value = "/user/{userId}")
    public ResponseVo<UserInfoVo> user(@PathVariable("userId") String userId){
        UserInfoVo userInfoVo = userInfoService.getUsreByUserId(userId);
        return ResponseVo.ok(userInfoVo);
    }
}
